<template>
    <el-form
        label-position="left"
        class="myform"
        status-icon
        :model="form"
        ref="refForm"
        :size="formSize"
        :rules="rules"
    >
        <el-form-item label="用户名称" prop="username">
            <el-input :prefix-icon="Avatar" v-model="form.username" type="text" placeholder="请输入用户名" autocomplete="off" />
        </el-form-item>
         <el-form-item label="登录密码" prop="password">
            <el-input :prefix-icon="Lock"  show-password v-model="form.password" type="password" placeholder="请输入密码"  autocomplete="off" />
        </el-form-item>
        <el-form-item class="lastitem">
            <div class="alinks">
                <router-link to="/register" class="litem color">无账号,去注册</router-link>
                <router-link :to="{name:'findpass'}"  class="litem bg">找回密码</router-link>
            </div>
        </el-form-item>

        <el-form-item class="lastitem" >
             <el-button type="success" @click="submitForm" class="btnblock">登录</el-button>
            <el-button type="danger" @click="resetForm" class="btnblock">重置</el-button>
        </el-form-item>
    </el-form>
</template>


<script setup>
import { onMounted, reactive, ref } from "vue"
import {Avatar, Lock } from "@element-plus/icons-vue"
import {reg} from '@/utils/validate'
import { ElMessage } from "element-plus"
import { useRouter } from "vue-router"
import {Http} from '@/api'
const router = useRouter()
const form = ref({})
const refForm = ref()
const formSize = ref("default")
const rules = reactive({
    username:[
        {
            required:true,message:"请输入用户名称",trigger: 'blur'
        }
    ],
    password:[
        {
            required:true,message:"请输入登录密码",trigger: 'blur'
        },
        {
            pattern:reg.pwd,message:'请输入6-16位数字加字母组合的密码', trigger: 'blur'
        }
    ]
})

// 重置按钮
const resetForm = ()=>{
    refForm.value.resetFields()
}

// 提交按钮
const submitForm = ()=>{
    refForm.value.validate(async (valid)=>{
        if(valid){
            // 开始登录  
            let res = await Http.login(form.value)
            if(res.code==200){
                router.push("/main")
                localStorage.setItem('username',form.value.username)
                localStorage.setItem('password',form.value.password)
                sessionStorage.setItem('autoToken',res.token)
            }
        }else{
            ElMessage.error("请输入有效的登录数据信息")
        }
    })
}
onMounted(()=>{
    console.log(router)
    const username = router.currentRoute.value.query.username;  // 获取query参数 
    if(username){
        form.value.username = username;
    }else{
        form.value.username = localStorage.getItem('username')
    }
    form.value.password = localStorage.getItem('password')
})
</script>